package com.gszkc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gszkc.constant.MessageConstant;
import com.gszkc.context.BaseContext;
import com.gszkc.dto.*;
import com.gszkc.entity.*;
import com.gszkc.exception.AddressBookBusinessException;
import com.gszkc.exception.OrderBusinessException;
import com.gszkc.exception.ShoppingCartBusinessException;
import com.gszkc.mapper.*;
import com.gszkc.result.PageResult;
import com.gszkc.service.OrderService;
import com.gszkc.utils.BaiduUtil;
import com.gszkc.vo.OrderPaymentVO;
import com.gszkc.vo.OrderStatisticsVO;
import com.gszkc.vo.OrderSubmitVO;
import com.gszkc.vo.OrderVO;
import com.gszkc.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
//    @Autowired
//    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BaiduUtil baiduUtil;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理业务异常(地址簿or购物车空 30行写逻辑3000行防小人原则 前端不可信原则！！！)
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook ==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查配送收货地址是否超出范围
        baiduUtil.checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        //查询当前购物车数据
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList ==null || shoppingCartList.size() ==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        //地址也拼装进去
        String address = addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail();
        orders.setAddress(address);

        orderMapper.insert(orders);

        //订单明细表插入N条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车
        shoppingCartMapper.deleteById(userId);
        //封装VO结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 分页查询历史订单
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQueryWithUser(int page, int pageSize, Integer status) {
        //明确需求,需要查订单和订单详情表 因此分页查询返回不是VO视图,后面在封装VO先正常查
        //一条订单对应多条订单明细,循环再查,用经典列表装载VO视图
        PageHelper.startPage(page,pageSize);//设置分页不多说
        //分页查询：根据用户ID和状态查询订单
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        //查询
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        //准备装载VO的列表
        ArrayList<OrderVO> list = new ArrayList<>();
        //判断如果查询的数据不为空则填装
        if (ordersPage != null || ordersPage.size() > 0){
            for (Orders orders : ordersPage) {
                //先根据ID查询对应的订单详情
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
                //新建VO并填充查询处理的 订单数据 和 订单详情数据
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                //添加到列表里面,over！
                list.add(orderVO);
            }
        }

        return new PageResult(ordersPage.getTotal(),list);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        Orders orders = orderMapper.getById(id);

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
//        //查询地址
//        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
//        String address = addressBook.getProvinceName() + addressBook.getCityName()
//                + addressBook.getDistrictName() + addressBook.getDetail();
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
//        //拼装地址 (在下单那里已经添加新代码)
//        orderVO.setAddress(address);

        return orderVO;
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void userCancelById(Long id) {
        Orders ordersTK = orderMapper.getById(id);
        //效验订单是否存在
        if (ordersTK == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态,排除其他不可退款状态 1代付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersTK.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersTK.getId());
        //已接单情况下要退款
        if (ordersTK.getStatus().equals(Orders.TO_BE_CONFIRMED)){
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
            //支付状态修改为已退款
            orders.setPayStatus(Orders.REFUND);
        }

        //更新订单为取消订单,取消时间,取消原因
        orders.setStatus(OrderVO.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orderMapper.update(orders);
    }

    /**
     * 用户再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        ArrayList<ShoppingCart> shoppingCartList = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    /**
     * 条件查询订单（分页展示）
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> ordersList = ordersPage.getResult();
        //新建返回VO类型,开始赋值查询数据和菜品数据拼接
        List<OrderVO> orderVOList = new ArrayList<>();
        //复制属性到
        if (!CollectionUtils.isEmpty(ordersList)){//如果不为空集合
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                String orderDish = getOrderDish(orders); //查询菜品数据整理返回字符串
                orderVO.setOrderDishes(orderDish);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    //还要查菜品数据
    private String getOrderDish(Orders orders){
        //根据ID查询订单详情返回列表
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        //在遍历循环取出菜品,格式定义为：宫保鸡丁 *3;
        List<String> orderDishList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            String dishOrNumber = orderDetail.getName() + " *" + orderDetail.getNumber();
            orderDishList.add(dishOrNumber);
        }
        return String.join("; ",orderDishList);
    }

    /**
     * 订单统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //订单状态,排除其他不可退款状态 1代付款 2待接单 3已接单 4派送中 5已完成 6已取消
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO statisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return statisticsVO;
    }


    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                        .id(ordersConfirmDTO.getId())
                        .status(Orders.CONFIRMED)
                        .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //只有待接单状态才可拒单
        Orders orderTK = orderMapper.getById(ordersRejectionDTO.getId());
        if (orderTK == null || !orderTK.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态如果为已支付需要退款在拒单
        if (orderTK.getPayStatus() ==Orders.PAID){
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
            //操作退款
            log.info("拒绝订单 退款给用户(" +BaseContext.getCurrentId() + "): " + orderTK.getAmount() + "元！");
        }


        //更新拒单操作
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())  //拒单原因
                .cancelTime(LocalDateTime.now())   //拒单时间
                .build();
        orderMapper.update(orders);
    }


    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //支付状态如果为已支付需要退款在拒单
        Orders orderTK = orderMapper.getById(ordersCancelDTO.getId());
        if (orderTK.getPayStatus() == Orders.PAID){
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
            //操作退款
            log.info("取消订单 退款给用户(" +BaseContext.getCurrentId() + "): " + orderTK.getAmount() + "元！");
        }

        //更新取消订单操作
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())//取消原因
                .cancelTime(LocalDateTime.now())   //取消时间
                .build();
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //只有待派送状态才可派送
        Orders orderPS = orderMapper.getById(id);
        if (orderPS == null || !orderPS.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //更新派单操作
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //只有派送中状态才可完成
        Orders orderWC = orderMapper.getById(id);
        if (orderWC == null || !orderWC.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //更新完成操作
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now()) //完成时间
                .build();
        orderMapper.update(orders);
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orderCD = orderMapper.getById(id);
        if (orderCD == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("userId",id);
        map.put("type",2);
        map.put("content","订单号:"+ orderCD.getNumber() + "请尽快处理！");
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "广商外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //推送消息 type orderId content
        Map map = new HashMap();
        map.put("type",1); //1来单提醒,2客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content", "新增订单："+ outTradeNo);

        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);


    }
}
